package com.gxwgy.wg2404.controller;


import com.gxwgy.wg2404.util.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 姚相国
 * @version 1.0
 * @className EnrollmentServlet
 * @date 2024/12/17 23:53
 */
@WebServlet({"/Enrollment"})
public class EnrollmentServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户名
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username"); // 从 Session 中获取用户名
        String eventId = request.getParameter("eventId"); // 从表单中获取活动 ID

        if (username == null) {
            response.sendRedirect("index.jsp"); // 如果未登录，跳转到登录页面
            return;
        }

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();

            // 1. 根据用户名查询用户 ID
            String getUserIdSql = "SELECT id FROM users WHERE username = ?";
            stmt = conn.prepareStatement(getUserIdSql);
            stmt.setString(1, username);
            rs = stmt.executeQuery();
            Integer userId = null;
            if (rs.next()) {
                userId = rs.getInt("id");
            }
            rs.close();
            stmt.close();

            if (userId == null) {
                response.getWriter().write("用户不存在，请重新登录！");
                return;
            }

            // 2. 检查是否已报名
            String checkSql = "SELECT COUNT(*) FROM enrollments WHERE user_id = ? AND event_id = ?";
            stmt = conn.prepareStatement(checkSql);
            stmt.setInt(1, userId);
            stmt.setString(2, eventId);
            rs = stmt.executeQuery();
            if (rs.next() && rs.getInt(1) > 0) {
                response.getWriter().write("您已报名此活动！");
                return;
            }
            rs.close();
            stmt.close();

            // 3. 检查名额是否已满
            String capacitySql = "SELECT capacity, (SELECT COUNT(*) FROM enrollments WHERE event_id = ?) AS enrolled FROM events WHERE id = ?";
            stmt = conn.prepareStatement(capacitySql);
            stmt.setString(1, eventId);
            stmt.setString(2, eventId);
            rs = stmt.executeQuery();
            if (rs.next()) {
                int capacity = rs.getInt("capacity");
                int enrolled = rs.getInt("enrolled");
                if (enrolled >= capacity) {
                    response.getWriter().write("报名失败，活动已满员！");
                    return;
                }
            }
            rs.close();
            stmt.close();

            // 更新活动的当前报名人数
            String updateEnrollmentSql = "UPDATE events SET current_enrollment = current_enrollment + 1 WHERE id = ?";
            stmt = conn.prepareStatement(updateEnrollmentSql);
            stmt.setString(1, eventId);
            stmt.executeUpdate();




            // 4. 插入报名记录
            String enrollSql = "INSERT INTO enrollments (user_id, event_id) VALUES (?, ?)";
            stmt = conn.prepareStatement(enrollSql);
            stmt.setInt(1, userId);
            stmt.setString(2, eventId);
            stmt.executeUpdate();

            // 5. 返回报名成功的消息
            response.getWriter().write("success");

        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("报名失败，请稍后再试！");
        } finally {
            DBUtil.close(conn, stmt, rs);
        }
    }
}


